<?php


namespace App\Api\Ipodsz;
use PhalApi\Api;

use PhalApi\Exception\BadRequestException;
use PhpOffice\PhpWord\TemplateProcessor;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

use Qiniu\Auth;


/**
 * 3023接口
 *   @desc 添加耳机
 */
class IpodsZ extends Api
{

    public function getRules()
    {
        return array(
            'addInfo' => array(),
            'addFsn' => array(),
            'switch_open' => array(),
            'switch_close' => array(),
            'get_switch' => array(),
        );
    }


    /**
     * 3023开
     */
    public function switch_open(){
        \PhalApi\DI()->cache->set('3023', 'on', 60*60*24*365);
        return '打开成功';
    }

    /**
     * 3023关
     */
    public function switch_close(){
        \PhalApi\DI()->cache->set('3023', 'off', 60*60*24*365);
        return '关闭成功';
    }

    /**
     * 3023状态
     */
    public function get_switch(){
        return \PhalApi\DI()->cache->get('3023');
    }

    /**
     * 消息格式化
     * @desc 消息格式化
     */
    public function sendText($data)
    {
        $ret = "";
        foreach ($data as $key => $value) {
            if( $value ){
                if ($key == 'ecid'){
                    if ( $value == '0000000000000000000000000000000000000000' ){
                        $ret .= "**" . $key . " :**  <font size=0 color=red>" . $value . "</font>  \n  ";
                    }else{
                        $ret .= "**" . $key . " :**  <font size=0 color=green>" . $value . "</font>  \n  ";
                    }
                }else if ($key == 'bfsn' ){
                    $where = array(
                        "username" => $data['帐号'],
                        "bfsn" => $data['bfsn']
                    );
                    $bfsn = \PhalApi\DI()->notorm->ipods_list_sz->where($where)->fetchAll();
                    if( $bfsn ){
                        if ( count($bfsn) > 1){
                            $ret .= "**" . $key . " :**  <font size=0 color=red>" . $value . "</font>  \n  ";
                        }else{
                            $ret .= "**" . $key . " :** " . $value . "  \n  ";
                        }
                    }
                }else{
                    $ret .= "**" . $key . " :** " . $value . "  \n  ";
                }
            }
        }
        return $ret;
    }



    /**
     * 添加耳仓
     * @desc 添加参数
     * @return array data 签名url
     * @exception 400 非法请求，参数传递错误
     */
    public function addFsn()
    {
 
        // 最简单的处理方式
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: *');

        $json = file_get_contents('php://input');
        $obj = json_decode($json, true);
        $who = $obj['who']; //操作员
        $token = $obj['token'];

        $fsn = $obj['fsn'];
        if( $fsn ){
            $fsn_info = \PhalApi\DI()->notorm->ipods_list_sz_fsn->where(array(
                'fsn' => $fsn,
                "username" => $obj['username']
            ))->fetchOne();


            if( $obj['type'] == 'in' ){
                $obj['in'] = date("Y-m-d H:i:s", time());
                $obj['in_note'] = $obj['note'];
            }
            if( $obj['type'] == 'by' ){
                $obj['by'] = date("Y-m-d H:i:s", time());
                $obj['by_note'] = $obj['note'];
            }
            if( $obj['type'] == 'out' ){
                $obj['out'] = date("Y-m-d H:i:s", time());
                $obj['out_note'] = $obj['note'];
            }
            if( $obj['type'] == 'back' ){
                $obj['back'] = date("Y-m-d H:i:s", time());
                $obj['back_note'] = $obj['note'];
            }

            $obj['update_time'] = date("Y-m-d H:i:s",time());
            $obj['date'] = date("Y-m-d",time());


    
            if( !$fsn_info ){
                $obj['create_time'] = date("Y-m-d H:i:s",time());

                $obj["autop"] = "yes";
                $typeList = array(
                    'in' => '入库',
                    'by' => '测试',
                    'out' => '出货',
                    'back' => '退货',
                );
                $text = array(
                    "帐号" => $obj['username'],
                    // "仓sn" => $fsn,
                    "状态" => "<font size=0 color=#00ff00>新增仓</font>",
                    "操作类型" => $typeList[$obj['type']],
                    "操  作  员" => $who,
                    "耳仓备注" => $obj['note'],
                    "操作时间" => date("Y-m-d H:i:s", time()),
                );

                
                if( false ){
                    $curl = new \PhalApi\CUrl();
                    $data3023_url = 'https://api.3023data.com/apple/coverage?key=VQ4AhsOeksYmpf6bh2ogCMnztvJvgpOd&sn=' . $fsn;
                    $res = $curl->get($data3023_url, 15000);
                    $obj['sn_data'] = $res;

                    $res = json_decode($res, true);

                    if( $res['code'] == 404 ){
                        $sn_data_cn = array(
                            "序例号" => $fsn,
                            "message" => $res['message']
                        );
                    }else{
                        $sn_data_cn = array(
                            "序例号" => $res['data']['sn'],
                            "型号" => $res['data']["model"],
                            "颜色" => $res['data']["color"],
                            "激活状态" => $res['data']['activated'] ? '是' : '否',
                            "购买日期" => $res['data']['purchase']['validated'],
                            "有效购买日期" => $res['data']['activation']['date'],
                            "保障情况" => $res['data']['coverage']['description'],
                            "借出设备" => $res['data']['locked'],
                            "已更换产品的序例号" => $res['data']['replaced'] ? "是" : '否',
                            "生产日期" => $res['data']['manufacture']['date']
                        );
                        $obj['replaced'] = $res['data']['replaced'] ? "是" : '否';
                    }

                    $sn_data_cn['3023余额'] = $res['balance'];
                    $obj['sn_data_cn'] = json_encode($sn_data_cn);
                }
                //存入数据库
                \PhalApi\DI()->notorm->ipods_list_sz_fsn->insert( $obj );
                $dingding = array_merge($text, $sn_data_cn);
                $this->ding($token, $this->sendText($dingding));

            }else{
                $obj["autop"] = "yes";
                $typeList = array(
                    'in' => '入库',
                    'by' => '测试',
                    'out' => '出货',
                    'back' => '退货',
                );
                $text = array(
                    "帐号" => $obj['username'],
                    "仓sn" => $fsn,
                    "状态" => "<font size=0 color=#ff0000>已存在</font>",
                    "操作类型" => $typeList[$obj['type']],
                    "操  作  员" => $who,
                    "耳仓备注" => $obj['note'],
                    "操作时间" => date("Y-m-d H:i:s", time()),
                );
                $this->ding($token, $this->sendText($text));
                \PhalApi\DI()->notorm->ipods_list_sz_fsn->where( 'id', $fsn_info['id'])->update( $obj );
            }   
        }
    }


    /**
     * 添加参数
     * @desc 添加参数
     * @return array data 签名url
     * @exception 400 非法请求，参数传递错误
     */
    public function addInfo()
    {
 
        // 最简单的处理方式
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: *');

        $json = file_get_contents('php://input');
        $obj = json_decode($json, true);
        $who = $obj['who'];
        $token = $obj['token'];

        $fsn = $obj['fsn'];
        if( $fsn ){
            $fsn_info = \PhalApi\DI()->notorm->ipods_list_sz_fsn->where(array(
                'fsn' => $fsn,
                "username" => $obj['username']
            ))->fetchOne();
    
            if( !$fsn_info ){
                $fsnInfo = array(
                    "fsn" => $fsn,
                    "username" => $obj['username'],
                    "date" => date("Y-m-d",time()),
                    "create_time" => date("Y-m-d H:i:s",time()),
                );
                if ( $obj['rightbaddr'] ) {
                    $fsnInfo['rightbaddr'] = $obj['rightbaddr'];
                }
                if ( $obj['leftbaddr'] ) {
                    $fsnInfo['leftbaddr'] = $obj['leftbaddr'];
                }
                \PhalApi\DI()->notorm->ipods_list_sz_fsn->insert( $fsnInfo );
            }else{
                $fsnInfo = array(
                    "update_time" => date("Y-m-d H:i:s",time()),
                );
                if ( $obj['rightbaddr'] ) {
                    $fsnInfo['rightbaddr'] = $obj['rightbaddr'];
                }
                if ( $obj['leftbaddr'] ) {
                    $fsnInfo['leftbaddr'] = $obj['leftbaddr'];
                }
                \PhalApi\DI()->notorm->ipods_list_sz_fsn->where( 'id', $fsn_info['id'])->update( $fsnInfo );
            }   
        }

        // if( $obj['ecid'] ){
        //     $where = array(
        //         "ecid" => $obj['ecid'],
        //         "username" => $obj['username'],
        //     );
        // }else{
            $where = array(
                "leftbaddr" => $obj['leftbaddr'],
                "rightbaddr" => $obj['rightbaddr'],
                "username" => $obj['username'],
            );
        // }

        $trueWhere = array();
        foreach ($where as $k=>$v){
            if($v) {
                $trueWhere[$k] = $v;
            }
        }

        // return $obj;

        if ( count($trueWhere) > 1 ) {

            if( $obj['type'] == 'in' ){
                $obj['in'] = date("Y-m-d H:i:s", time());
                $obj['in_note'] = $obj['note'];
            }
            if( $obj['type'] == 'by' ){
                $obj['by'] = date("Y-m-d H:i:s", time());
                $obj['by_note'] = $obj['note'];
            }
            if( $obj['type'] == 'out' ){
                $obj['out'] = date("Y-m-d H:i:s", time());
                $obj['out_note'] = $obj['note'];
            }
            if( $obj['type'] == 'back' ){
                $obj['back'] = date("Y-m-d H:i:s", time());
                $obj['back_note'] = $obj['note'];
            }

            $obj['update_time'] = date("Y-m-d H:i:s",time());
            $obj['date'] = date("Y-m-d",time());

            $ishave = \PhalApi\DI()->notorm->ipods_list_sz->where($trueWhere)->fetchOne();
            if($ishave){
                $obj["autop"] = "yes";
                \PhalApi\DI()->notorm->ipods_list_sz->where('id',$ishave['id'])->update($obj);
                // $token = '6c73e2a96b719badbbda3b4cc593aa5c5a56af38a5dcf8d88232ba1becdfa857';
                $typeList = array(
                    'in' => '入库',
                    'by' => '测试',
                    'out' => '出货',
                    'back' => '退货',
                );

                $text = array(
                    "帐号" => $obj['username'],
                    $obj['leftbaddr'] ? '左耳' : "右耳" =>  $obj['leftbaddr'] ? $obj['leftbaddr'] : $obj['rightbaddr'],
                    "bfsn" => $obj['bfsn'],
                    "ecid" => $obj['ecid'],
                    "状态" => "<font size=0 color=#ff0000>耳机已经存在</font>",
                    "操作类型" => $typeList[$obj['type']],
                    "操  作  员" => $who,
                    "耳机备注" => $obj['note'],
                    "操作时间" => date("Y-m-d H:i:s", time()),
                    "入库备注" => "[ " . $ishave['in_note'] . ":" . $ishave['create_time'] . " ]",
                );
                // if ( $ishave['update_time'] > date("Y-m-d H:i:s", time() - 30 * 1) ) {
                //     $this->ding($token, $this->sendText($text));
                //     return "ishas";
                // }
                $this->ding($token, $this->sendText($text));
                return 'ishas';
            }
            $obj['date'] = date("Y-m-d",time());
            $obj['update_time'] = date("Y-m-d H:i:s",time());
            $obj['create_time'] = date("Y-m-d H:i:s",time());

            $typeList = array(
                'in' => '入库',
                'by' => '测试',
                'out' => '出货',
                'back' => '退货',
            );

            $text = array(
                "帐号" => $obj['username'],
                $obj['leftbaddr'] ? '左耳' : "右耳" =>  $obj['leftbaddr'] ? $obj['leftbaddr'] : $obj['rightbaddr'],
                "bfsn" => $obj['bfsn'],
                "ecid" => $obj['ecid'],
                "状态" => "<font size=0 color=#00ff00>新增耳机</font>",
                "操作类型" => $typeList[$obj['type']],
                "操 作 员" => $who,
                "耳机备注" => $obj['note'],
                "操作时间" => date("Y-m-d H:i:s", time()),
            );
            $this->ding($token, $this->sendText($text));
            return \PhalApi\DI()->notorm->ipods_list_sz->insert($obj);
        }
    }

    /**
     * 钉钉推送
     */

    public function ding($token, $msg){
        //这里是钉钉提示的开始
        $curl = new \PhalApi\CUrl();
        // 设置请求的头部信息。
        $curl->setHeader(array('Content-Type' => 'application/json'));
        // 设置curl选项
        $postDate = array(
            "msgtype" => "markdown",
            "markdown" => array(
                "title" => "耳机信息",
                "text" => "# 耳机参数 # \n\n" . $msg
            )
        );
        $url = "https://oapi.dingtalk.com/robot/send?access_token=$token";
        $curl->post($url, json_encode($postDate),2000);
    }

}
